﻿Namespace db

	Public Class [datatype]

		Dim value As Object

		ReadOnly Property [get] As Object
			Get
				'If IsDBNull(value) Then Return value
				Return If(value = Nothing, DBNull.Value, value)
			End Get
		End Property

		Sub [set](value As Object)
			If TypeOf value Is datatype Then
				Me.value = CType(value, datatype).value
				Return
			End If
			Me.value = value
		End Sub

		Sub import(DataWindow As DataWindow, Field As String)
			Me.set(DataWindow.Fields(Field).Value)
		End Sub
	End Class

	Public Class [char] : Inherits datatype

	End Class

	Public Class [varchar] : Inherits datatype

	End Class

	Public Class [int] : Inherits datatype

	End Class

	Public Class [bigint] : Inherits datatype

	End Class

	Public Class [numeric] : Inherits datatype

	End Class

	Public Class [datetime] : Inherits datatype

	End Class

	Public Class table

		Sub New()

		End Sub

		Protected row As DataRow

		Overridable ReadOnly Property tablename As String
			Get
				Return Me.GetType().Name
			End Get
		End Property

		Protected InTransaction As Boolean = False

		Public Sub save(Token As Token, Optional TopLevel As Boolean = True)
			If Not InTransaction AndAlso TopLevel Then Token.BeginTran() : InTransaction = True
			Dim Params As New List(Of datatype)
			Dim Fields As String = ""
			For Each p In Me.GetType.GetProperties
				Dim Value = p.GetValue(Me, Nothing)
				If TypeOf Value Is datatype AndAlso Not p.Name = "rowid" Then
					Fields &= ",@" & p.Name
					Params.Add(Value)
				End If
			Next
			Fields = Mid(Fields, 2)
			Token.ExecSQL("insert into " & tablename & "(" & Fields.Replace("@", "") & ") values (" & Fields & ")", Params)
			AfterSave(Token)
			If InTransaction AndAlso TopLevel Then Token.CommitTran() : InTransaction = False
		End Sub

		Overridable Sub AfterSave(Token As Token)

		End Sub

		Sub import(DataWindow As DataWindow)
			For Each p In Me.GetType.GetProperties
				Dim Value = p.GetValue(Me, Nothing)
				If TypeOf Value Is datatype Then
					If DataWindow.ContainsField(p.Name) Then
						Dim t As datatype = p.GetValue(Me, Nothing)
						t.set(DataWindow.Fields(p.Name).Value)
						'p.SetValue(Me, DataWindow.Fields(p.Name).Value, Nothing)
					End If
				End If
			Next
		End Sub

	End Class

End Namespace